#coding: utf-8
from django.db import models

class Category( models.Model ):
    name = models.CharField( max_length = 50, unique = True, verbose_name = '名称' )
    parent = models.ForeignKey( 'self', null = True, blank = True, verbose_name = '父分类' )
    count = models.PositiveIntegerField( default = 0, verbose_name = '计数' )
    
    def __unicode__( self ):
        return self.name
    
    def category_and_sub( self ):
        childlist = list( self.category_set.all() )        
        entry = { self: childlist }
        return entry
    
    def categoryTree( self ):
        childlist = list( self.category_set.all() )        
        if childlist != []:
            index = 0
            while ( index < len( childlist ) ):
                child = childlist[ index ]
                childlist[ index ] = child.categoryTree()
                index += 1
        tree = { self: childlist }
        return tree

class Tag( models.Model ):
    name = models.CharField( max_length = 50, verbose_name = '名称' )
    
    def __unicode__( self ):
        return self.name
    
    @staticmethod
    def check_and_save( tagnames ):
        for tagname in tagnames:
            try:
                tag = Tag.objects.get( name = tagname )
            except Tag.DoesNotExist:
                tag = Tag( name = tagname )
            else:
                tag.save()


